package com.zmwx.auth.domain.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zmwx.auth.common.enums.IsDeletedFlagEnum;
import com.zmwx.auth.domain.convert.AuthPermissionBOToConverter;
import com.zmwx.auth.domain.entityDO.AuthPermissionBO;
import com.zmwx.auth.domain.redis.RedisUtil;
import com.zmwx.auth.domain.service.AuthPermissionDomainService;
import com.zmwx.auth.infra.basic.entity.AuthPermission;
import com.zmwx.auth.infra.basic.service.AuthPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {
   @Resource
    AuthPermissionService authPermissionService;
    @Resource
    private RedisUtil redisUtil;

    private String authPermissionPrefix = "auth.permission";

    @Override
    public boolean addPermission(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission=
                AuthPermissionBOToConverter.INSTANCE.convertBOToEntity(authPermissionBO);
        authPermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        return   authPermissionService.insert(authPermission)>0;
    }

    @Override
    public boolean updatePermission(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission= AuthPermissionBOToConverter.INSTANCE.convertBOToEntity(authPermissionBO);
        Integer count = authPermissionService.update(authPermission);
        return count>0;
    }

    @Override
    public boolean deletePermission(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = new AuthPermission();
        authPermission.setId(authPermissionBO.getId());
        authPermission.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        Integer count = authPermissionService.update(authPermission);
        return count > 0;
    }

    @Override
    public List<String> getPermission(String userName) {
        String permissionKey=redisUtil.buildKey(authPermissionPrefix,userName);
        String permissionValue = redisUtil.get(permissionKey);
        if (StringUtils.isBlank(permissionValue)) {
            return Collections.emptyList();
        }
        List<AuthPermission> permissionList=
                new Gson().fromJson(
                        permissionValue,new TypeToken<List<AuthPermission>>(){}.getType()
                ); //把字符串转为 对象
        List<String> authList=permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        if(log.isInfoEnabled()){
            log.info("****************authList:{}",authList);
        }
        return authList;
    }
}
